import React from 'react'
import imgSrc from '../imgs/pexels-ron-lach-7858743.jpg'
import { useState } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { message, Upload } from 'antd'
export function ImgRight() {
  const [hasImg] = useState('')
  return imgSrc == '' ? (
    <div
      className="md:m-0  border-slate-500 border-2 bg-cover bg-center
         md:w-1/2 sm:w-full sm:m-16 sm:h-screen"
      style={{
        backgroundImage: `url(${hasImg})`,
      }}
    ></div>
  ) : (
    <UploadImg />
  )
}

export function UploadImg() {
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState()

  //获取图片的base64
  const getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  //上传之前的限制
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
    }
    return isJpgOrPng && isLt2M
  }

  //上传回调
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false)
        setImageUrl(url)
      })
    }
  }

  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
        color: '#fff',
      }}
      type="button"
    >
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload Imgs
      </div>
    </button>
  )
  return (
    <div
      style={{ height: '90vh' }}
      className="flex flex-col justify-center items-center w-1/2 "
    >
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt="avatar"
            style={{
              width: '100%',
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
    </div>
  )
}
